package com.gz.thread.juc.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池的几大方法
 */
public class Demo1 {
    public static void main(String[] args) {

        //    cachedThreadPool(Executors.newCachedThreadPool());
        //    fixedThreadPool(Executors.newFixedThreadPool(5));
        singleThreadPool(Executors.newSingleThreadExecutor());
//        Executors.newFixedThreadPool(5);
//        Executors.newSingleThreadExecutor();
//        Executors.newSingleThreadScheduledExecutor();
//        Executors.newWorkStealingPool();
    }


    /**
     * 缓存线程池。具有良好的伸缩性，根据具体情况创建多个线程
     * @param executorService   cachedThreadPool(Executors.newCachedThreadPool());
     */
    public static void cachedThreadPool(ExecutorService executorService) {
        try {
            for (int i = 0; i < 10; i++) {
                int finalI = i;
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "---cached thread pool" + finalI);
                });
            }
        } finally {
            executorService.shutdown();
        }
    }

    /**
     * 创建固定数量的线程池
     * @param executorService    fixedThreadPool(Executors.newFixedThreadPool(5));
     */
    public static void fixedThreadPool(ExecutorService executorService) {
        try {
            for (int i = 0; i < 10; i++) {
                int finalI = i;
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "---fixed thread pool");
                });
            }
        } finally {
            executorService.shutdown();
        }
    }

    /**
     * 创建唯一的线程
     * @param executorService    singleThreadPool(Executors.newSingleThreadExecutor());
     */
    public static void singleThreadPool(ExecutorService executorService) {
        try {
            for (int i = 0; i < 10; i++) {
                int finalI = i;
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "---singleThreadPool");
                });
            }
        } finally {
            executorService.shutdown();
        }
    }
}
